//
//  FindPwdView.swift
//  maosheng
//
//  Created by 何海涛 on 2019/8/15.
//

import Foundation
import UIKit

protocol FindPwdViewDelegate {
    func sendResetPwd(_ model: FindPasswordLoginRequest)
}

class FindPwdView: UIView, UITextFieldDelegate {
    
    var delegate: FindPwdViewDelegate?
    var isRegist : Bool = false
    lazy var icon: UIImageView = {
        var img = UIImageView(image: UIImage(named: "login_find_password"))
        self.addSubview(img)
        img.snp.makeConstraints({ (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(40)
        })
        return img
    }()
    
    lazy var inputMobile: LoginInputLabelView = {
        var txt = LoginInputLabelView()
        txt.render(text: "手机号：", placeHolder: "请输入手机号", keyboard: .phonePad, showSend: false)
        txt.withBottomSeparater()
        self.addSubview(txt)
        txt.snp.makeConstraints({ (make) in
            make.left.equalTo(self).offset(40)
            make.right.equalTo(self).offset(-40)
            make.top.equalTo(self.icon.snp.bottom).offset(60)
            make.height.equalTo(44)
        })
        return txt
    }()
    
    lazy var inputCode: LoginInputLabelView = {
        var txt = LoginInputLabelView()
        txt.render(text: "验证码：", placeHolder: "请输入验证码", keyboard: .default, showSend: true)
        txt.withBottomSeparater()
        self.addSubview(txt)
        txt.snp.makeConstraints({ (make) in
            make.left.right.height.equalTo(self.inputMobile)
            make.top.equalTo(self.inputMobile.snp.bottom).offset(20)
        })
        return txt
    }()
    
    lazy var inputPwd: LoginInputLabelView = {
        var txt = LoginInputLabelView()
        txt.render(text: isRegist ? "密码：" : "新密码：", placeHolder: "请输入6-20位数字或者字母", keyboard: .default, showSend: false)
        txt.withBottomSeparater()
        txt.txt.isSecureTextEntry = true
        self.addSubview(txt)
        txt.snp.makeConstraints({ (make) in
            make.left.right.height.equalTo(self.inputCode)
            make.top.equalTo(self.inputCode.snp.bottom).offset(20)
        })
        return txt
    }()
    
    lazy var btnLogin: UIButton = {
        var btn = UIButton()
        btn.setMutexColor(colorPairs: MutexColors.Disable)
        btn.setTitle(isRegist ? "注册" : "找回密码", for: .normal)
        btn.setCorner(22)
        btn.titleLabel?.font = VS.font18
        self.addSubview(btn)
        btn.snp.makeConstraints({ (make) in
            make.top.equalTo(self.inputPwd.snp.bottom).offset(50)
            make.left.equalTo(self).offset(40)
            make.right.equalTo(self).offset(-40)
            make.height.equalTo(44)
        })
        return btn
    }()
    
    func render() {
        inputMobile.txt.delegate = self
        inputCode.txt.delegate = self
        inputPwd.txt.delegate = self
        inputMobile.txt.addTarget(self, action: #selector(textFieldValueChanged), for: .editingChanged)
        inputCode.txt.addTarget(self, action: #selector(textFieldValueChanged), for: .editingChanged)
        inputPwd.txt.addTarget(self, action: #selector(textFieldValueChanged), for: .editingChanged)
        btnLogin.addTarget(self, action: #selector(btnLoginClicked), for: .touchUpInside)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        _ = validateInput(showError: false)
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        _ = validateInput(showError: false)
    }
    
    @objc
    func textFieldValueChanged() {
        _ = validateInput(showError: false)
    }
    
    @objc
    func btnLoginClicked() {
        if let model = validateInput(showError: true) {
            delegate?.sendResetPwd(model)
        }
    }
    
    fileprivate func validateInput(showError: Bool) -> FindPasswordLoginRequest? {
        // model binder
        let model = FindPasswordLoginRequest()
        let results = ModelBinder.bindModel(model, rules: self, view: self)
        let hasError = results.errors.count > 0
        if showError && hasError { self.handleError(errors: results.errors) }
        
        // login btn style
        self.btnLogin.setMutexColor(colorPairs: hasError ? MutexColors.Disable : MutexColors.RedReverse)
        
        // return
        return hasError ? nil : results.model
    }
}

// validation
extension FindPwdView: IValidationRuleProvider {
    
    func getValidateRules() -> [ValidationRule] {
        return [
            RequiredValidationRule(memberName: "mobile", displayName: "手机号"),
            RegexValidationRule(memberName: "mobile", pattern: Regex.MobilePattern, errorMessage: "手机号格式有误"),
            RequiredValidationRule(memberName: "verifyCode", displayName:"验证码"),
            RequiredValidationRule(memberName: "password", displayName: "密码"),
            RegexValidationRule(memberName: "password", pattern: "^[0-9a-zA-Z]{6,20}$", errorMessage: "请输入6-20位数字或者字母")
        ]
    }
}

extension FindPwdView: IViewDataBindingProtocol {
    
    func getDataMappings() -> [ViewDataMapping] {
        return [
            ViewDataMapping(memberName: "mobile", valueProvider: { () -> AnyObject? in
                return self.inputMobile.txt.text as AnyObject
            }),
            ViewDataMapping(memberName: "verifyCode", valueProvider: { () -> AnyObject? in
                return self.inputCode.txt.text as AnyObject
            }),
            ViewDataMapping(memberName: "password", valueProvider: { () -> AnyObject? in
                return self.inputPwd.txt.text as AnyObject
            })
        ]
    }
}

extension FindPwdView: ValidationErrorBehaviorProtocol {
    
    func handleError(errors: [ValidationResult]) {
        if errors.first != nil {
            self.makeToast(errors.first!.errorMessage)
        }
    }
}


